<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <label class="el-form-item-label">实验室</label>
        <el-select
          v-model="query.labId"
          placeholder="请选择实验室"
          style="width: 185px;"
          clearable
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        >
          <el-option
            v-for="item in labs"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
        <!-- <label class="el-form-item-label">创建者</label> -->
        <!-- <el-input v-model="query.creatorId" clearable placeholder="创建者" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" /> -->
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog
        :close-on-click-modal="false"
        :before-close="crud.cancelCU"
        :visible.sync="crud.status.cu > 0"
        :title="crud.status.title"
        width="650px"
      >
        <el-form ref="form" :model="form" :rules="rules" label-width="140px">
          <el-form-item label="实验室" prop="labId">
            <el-select
              v-model="form.labId"
              style="width: 423px;"
              placeholder="请选择实验室"
            >
              <el-option
                v-for="item in addLabs"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <div style="margin: 10px 0; color:#448ef7;">通用预约时间设置：</div>
          <el-form-item label="月" prop="months">
            <el-select
              v-model="form.months"
              style="width: 423px;"
              size="small"
              multiple
              placeholder="请选择月份"
            >
              <el-option
                v-for="item in months"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="周" prop="weeks">
            <el-select
              v-model="form.weeks"
              style="width: 423px;"
              size="small"
              multiple
              placeholder="请选择周"
            >
              <el-option
                v-for="item in weekList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="至少提前预约时间" prop="advanceBookTime">
            <el-input-number
              v-model="form.advanceBookTime"
              style="width: 270px;"
              :min="0"
              :step="0.5"
            />
            小时
          </el-form-item>
          <el-form-item label="可提前取消时间" prop="cancelTime">
            <el-input-number
              v-model="form.cancelTime"
              style="width: 270px;"
              :min="0"
              :step="0.5"
            />
            小时
          </el-form-item>
          <el-form-item label="最长可以预约时间" prop="maxTime">
            <el-input-number
              v-model="form.maxTime"
              style="width: 270px;"
              :min="0"
              :step="0.5"
            />
            小时
          </el-form-item> -->
          <el-form-item label="选择通用时间段" prop="bookTime">
            <full-calendar
              id="selectCalendar1"
              ref="selectCalendar1"
              :events="events1"
              :config="agendaDayConfig"
            />
          </el-form-item>

          <!-- <div style="margin: 10px 0;color:#448ef7;">特殊预约时间设置：</div>
          <el-form-item label="日期" prop="date_arr">
            <el-date-picker
              v-model="form.dates"
              size="small"
              type="daterange"
              :picker-options="pickerOptions"
              value-format="yyyy-MM-dd"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>
          <el-form-item label="选择特殊时间段">
            <full-calendar
              id="selectCalendar2"
              ref="selectCalendar2"
              :events="events2"
              :config="config"
            />
          </el-form-item> -->

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button
            :loading="crud.status.cu === 2"
            type="primary"
            @click="crud.submitCU"
          >确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table
        ref="table"
        v-loading="crud.loading"
        :data="crud.data"
        size="small"
        style="width: 100%;"
        @selection-change="crud.selectionChangeHandler"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="55" />
        <el-table-column prop="labId" label="实验室" :formatter="formatterLab"/>
        <el-table-column prop="months" label="月" :formatter="formatterMonths"/>
        <el-table-column prop="weeks" label="周" :formatter="formatterWeeks"/>
        <el-table-column prop="bookTime" label="通用时间段">
          <template slot-scope="scoped">
            <div v-for="(item,i ) in JSON.parse(scoped.row.bookTime)" :key="i">
              <span>{{ item.start }}</span> - <span>{{ item.end }}</span>
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="dates" label="特殊时间日期" /> -->
        <!-- <el-table-column prop="specialTime" label="特殊时间段" /> -->
        <el-table-column
          v-if="checkPer(['admin', 'labTime:edit', 'labTime:del'])"
          label="操作"
          width="150px"
          align="center"
        >
          <template slot-scope="scope">
            <udOperation :data="scope.row" :permission="permission" />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import { FullCalendar } from 'vue-full-calendar'
import 'fullcalendar/dist/fullcalendar.css'
import getAllUserAndLabs from '@/mixins/getAllUserAndLabs.js'
import crudLabTime from '@/api/labTime'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'

const defaultForm = {
  id: null,
  labId: null,
  months: [],
  weeks: [],
  // advanceBookTime: null,
  // cancelTime: null,
  // maxTime: null,
  bookTime: [],
  event:[]
  // dates: [],
  // specialTime: [],
}
export default {
  name: 'LabTime',
  components: {
    pagination,
    crudOperation,
    rrOperation,
    udOperation,
    FullCalendar
  },
  mixins: [presenter(), header(), form(defaultForm), crud(), getAllUserAndLabs],
  cruds() {
    return CRUD({
      title: '实验室可预约时间',
      url: 'api/labTime',
      idField: 'id',
      sort: 'id,desc',
      crudMethod: { ...crudLabTime }
    })
  },
  data() {
    const limtTime = (rule, value, callback) => {
      if (value <= 0) {
        return callback(new Error('请设置时间'))
      }
      callback()
    }
    const that = this
    return {
      addLabs:[],
      permission: {
        add: ['admin', 'labTime:add'],
        edit: ['admin', 'labTime:edit'],
        del: ['admin', 'labTime:del']
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now()
        }
      },
      agendaDayConfig: {
        locale: 'zh-cn',
        defaultView: 'agendaDay',
        allDaySlot: false,
        slotDuration: '00:10:00',
        slotLabelFormat: 'HH:mm',
        minTime: '00:00:00',
        maxTime: '24:00:00',
        slotEventOverlap: false, // 事件是否允许重叠
        scrollTime: '08:00:00',
        header: {
          left: '',
          center: '',
          right: ''
        },
        selectAllow: function(clickInfo) {
          var start = clickInfo.start.unix() - 28800
          var end = clickInfo.end.unix() - 28800
          var start_temp, end_temp
          var canSelect = true
          if (that.events1.length > 0) {
            that.events1.forEach(item => {
              if (typeof item.start === 'string') {
                start_temp = new Date(item.start).getTime() / 1000
                end_temp = new Date(item.end).getTime() / 1000
              } else {
                start_temp = item.start.unix() - 28800
                end_temp = item.end.unix() - 28800
              }
              if (
                (start >= start_temp && start <= end_temp) ||
                (end >= start_temp && end <= end_temp) ||
                (start < start_temp && end > end_temp)
              ) {
                canSelect = false
              }
            })
          }
          return canSelect
        },
        select: function(startDate, endDate, allDay, jsEvent, view) {
          // 选中
          const start = startDate._i // [年， 月，日， 时，分，秒]
          const end = endDate._i
          if (jsEvent.type === 'agendaDay') {
            const startAt = '' + that.getFulldate(start[3]) +':'+ that.getFulldate(start[4])
            const endAt = '' + that.getFulldate(end[3]) + ':'+that.getFulldate(end[4])
            const IdTime = new Date().getTime()
            that.form.bookTime.push({
              start: startAt,
              end: endAt,
              resourceId:IdTime
            })
            that.events1.push({
              resourceId: IdTime,
              title: '已选择(点击删除)',
              start: startDate,
              end: endDate,
              color: 'blue',
              textColor: 'black',
              editable: false,
              selectable: false
            })
            that.form.event = that.events1
          }
        },
        eventClick(event, jsEvent, view) {
          // 有颜色部分点击
          that.events1.forEach((item, index) => {
            if (item.resourceId === event.resourceId) {
              that.events1.splice(index, 1)
            }
          })
          that.form.event = that.events1
          that.form.bookTime.forEach((item, index)=>{
            if (item.resourceId == event.resourceId) {
              that.form.bookTime.splice(index, 1)
            }
          })
        }
      },
      config: {
        locale: 'zh-cn',
        defaultView: 'agendaDay',
        allDaySlot: false,
        slotDuration: '00:10:00',
        slotLabelFormat: 'HH:mm',
        minTime: '00:00:00',
        maxTime: '24:00:00',
        slotEventOverlap: false, // 事件是否允许重叠
        scrollTime: '08:00:00',
        header: { left: '', center: '', right: '' },
        selectAllow: function(clickInfo) {
          var start = clickInfo.start.unix() - 28800
          var end = clickInfo.end.unix() - 28800
          var start_temp, end_temp
          var canSelect = true
          if (that.events2.length > 0) {
            that.events2.forEach(item => {
              if (typeof item.start === 'string') {
                start_temp = new Date(item.start).getTime() / 1000
                end_temp = new Date(item.end).getTime() / 1000
              } else {
                start_temp = item.start.unix() - 28800
                end_temp = item.end.unix() - 28800
              }
              if (
                (start >= start_temp && start <= end_temp) ||
                (end >= start_temp && end <= end_temp) ||
                (start < start_temp && end > end_temp)
              ) {
                canSelect = false
              }
            })
          }
          return canSelect
        },
        select: function(startDate, endDate, allDay, jsEvent, view) {
          const start = startDate._i // [年， 月，日， 时，分，秒]
          const end = endDate._i
          if (jsEvent.type === 'agendaDay') {
            const startAt = '' + that.getFulldate(start[3]) + that.getFulldate(start[4])
            const endAt = '' + that.getFulldate(end[3]) + that.getFulldate(end[4])
            that.form.specialTimeF.push({
              start: startAt,
              end: endAt
            })
            that.events2.push({
              resourceId: new Date().getTime(),
              title: '已选择(点击删除)',
              start: startDate,
              end: endDate,
              color: 'blue',
              textColor: 'black',
              editable: false,
              selectable: false
            })
          }
        },
        eventClick(event, jsEvent, view) {
          that.events2.forEach((item, index) => {
            if (item.resourceId === event.resourceId) {
              that.events2.splice(index, 1)
            }
          })
        }
      },
      apparatus: [],
      rules: {
        labId: [
          { required: true, message: '请选择实验室', trigger: 'change' }
        ],
        months: [
          { required: true, message: '请选择月', trigger: 'change' }
        ],
        weeks: [{ required: true, message: '请选择周', trigger: 'change' }],
        advanceBookTime: [{ required: true, trigger: 'change', validator: limtTime }],
        maxTime: [{ required: true, trigger: 'change', validator: limtTime }],
        cancelTime: [{ required: true, trigger: 'change', validator: limtTime }],
        bookTime: [{ required: true, message: '请选择通用时间段', trigger: 'blur' }]
      },
      months: [
        { label: '一月', value: '1' },
        { label: '二月', value: '2' },
        { label: '三月', value: '3' },
        { label: '四月', value: '4' },
        { label: '五月', value: '5' },
        { label: '六月', value: '6' },
        { label: '七月', value: '7' },
        { label: '八月', value: '8' },
        { label: '九月', value: '9' },
        { label: '十月', value: '10' },
        { label: '十一月', value: '11' },
        { label: '十二月', value: '12' }
      ],
      events1: [],
      events2: [],
      weekList: [
        { label: '周一', value: '1' },
        { label: '周二', value: '2' },
        { label: '周三', value: '3' },
        { label: '周四', value: '4' },
        { label: '周五', value: '5' },
        { label: '周六', value: '6' },
        { label: '周日', value: '7' }
      ],
      queryTypeOptions: [
        { key: 'locate', display_name: '实验室位置' },
        { key: 'creatorId', display_name: '创建者' }
      ]
    }
  },
  created() {
    this.getLabs()
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
     /** 新建 - 之前 */
    [CRUD.HOOK.beforeToAdd](){
      this.events1 = []
      this.addLabs = this.labs.filter(item=>this.crud.data.every(v=>v.labId != item.id))
    },
      /** 编辑 - 之前 */
    [CRUD.HOOK.beforeToEdit](data,val){
      this.events1 = JSON.parse(val.event)
      this.crud.form.weeks =JSON.parse(val.weeks)
      this.crud.form.months =JSON.parse(val.months)
      this.crud.form.bookTime =JSON.parse(val.bookTime)
      this.addLabs = this.labs
    },
    getFulldate(time) {
      if (time < 10) {
        time = '0' + time
      }
      return time
    },
    formatterLab(row) {
      const data = this.labs.find(lab => lab.id == row.labId)
      if (data) {
        return data.name
      }
    },
    formatterMonths(row){
     return JSON.parse(row.months).map(item =>{
      if(item==1){
        return '一月'
      }else if(item==2){
        return '二月'
      }else if(item==3){
        return '三月'
      }else if(item==4){
        return '四月'
      }else if(item==5){
        return '五月'
      }else if(item==6){
        return '六月'
      }else if(item==7){
        return '七月'
      }else if(item==8){
        return '八月'
      }else if(item==9){
        return '九月'
      }else if(item==10){
        return '十月'
      }else if(item==11){
        return '十一月'
      }else if(item==12){
        return '十二月'
      }
     }).join(',')
    },
    formatterWeeks(row){
      return JSON.parse(row.weeks).map(item =>{
      if(item==1){
        return '周一'
      }else if(item==2){
        return '周二'
      }else if(item==3){
        return '周三'
      }else if(item==4){
        return '周四'
      }else if(item==5){
        return '周五'
      }else if(item==6){
        return '周六'
      }else if(item==7){
        return '周日'
      }
     }).join(',')
    }
  }
}
</script>

<style scoped lang="scss">
.el-dialog__wrapper ::v-deep .el-dialog {
  overflow: hidden;
  .fc-time-grid .fc-slats td:nth-child(2) {
    background-color: #eaf4fe;
    background-color: #fff;
  }

  .fc-header-toolbar {
    display: none;
  }
  .fc-widget-header {
    display: none;
  }
  .fc-time-grid-container {
    height:300px !important;
  }
  .fc {
    width: 90%;
  }
}
</style>
